<template>
  <div class="editor">
    <div class="cus-editor" style="position: relative;margin: 0 auto;">
      <el-upload
        style="display: inline-block;position: absolute; font-size: 20px;top:2px;left: 696px;color: rgb(153,153,153)"
        :http-request="handleMainImgUploadFile"
        :show-file-list="false"
      >
        <span class="el-icon-picture" style=""></span>
      </el-upload>
      <div ref="editor" id="editor" style="text-align: left;"></div>
    </div>
  </div>
</template>

<script>
import { MobileEditorMenus } from "./editorConfig";
import Editor from "wangeditor";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";

export default {
  props: {
    initContent: {
      default: "",
      type: String,
      required: true
    }
  },
  components: {},
  name: "index",
  data() {
    return {
      imageData: {},
      editor: undefined,
      // editorContent: '',
      imgSelectVisible: false
    };
  },
  methods: {
    handleMainImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            const imgUrl = "https://asset.fanghaowu.com/" + fileKey;
            this.editor.cmd.do(
              "insertHtml",
              '<img src="' + imgUrl + '" style="max-width:100%;"/>'
            );
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    initEditor() {
      this.editor.customConfig.menus = MobileEditorMenus;
      this.editor.customConfig.onchange = html => {
        this.$emit("change", html);
      };
      this.editor.customConfig.debug = true;
      this.editor.customConfig.zIndex = 100;
    }
  },
  mounted() {
    this.editor = new Editor("#editor");
    this.initEditor();
    this.editor.create();
    this.editor.txt.html(this.initContent || "请输入内容");
  }
};
</script>

<style scoped></style>
